<template>
  <div class="app-container">
    <div class="orderCenterList">
      <el-button style="width: 100%; height: 40px; margin-top: 35px" type="primary" @click="addAction" :icon="Plus">
        新建工单
      </el-button>
      <div style="margin: 10px 0 15px">工单池</div>
      <div>
        <ul style="border-bottom: 1px solid #ccc">
          <li v-for="(item, index) in lists" :key="index" @click="listClick(item.label, item.value, false)"
            :class="currentTitle == item.label ? 'bgColor' : ''">
            <span>{{ item.label }}</span>
            <span v-if="item.label == '我的工单'">{{
              orderCount.myself_count <= 99 ? orderCount.myself_count : "0" }}</span>
                <span v-if="item.label == '未处理工单'">{{
                  orderCount.unprocessed_count <= 99 ? orderCount.unprocessed_count : "0" }}</span>
                    <span v-if="item.label == '进行中工单'">{{
                      orderCount.processing_count <= 99 ? orderCount.processing_count : "0" }}</span>
                        <span v-if="item.label == '已完成工单'">{{
                          orderCount.completed_count <= 99 ? orderCount.completed_count : "0" }}</span>
                            <!-- <span>{{
              item.label == "未处理工单"
                ? orderCount.unprocessed_count
                : item.label == "进行中工单"
                ? orderCount.processing_count
                : orderCount.completed_count
            }}</span> -->
          </li>
        </ul>
      </div>
      <div style="margin: 10px 0 15px">问题工单</div>
      <div>
        <ul style="border-bottom: 1px solid #ccc">
          <li v-for="(item, index) in problemList" :key="index" @click="listClick(item.label, item.value, true)"
            :class="currentTitle == item.label ? 'bgColor' : ''">
            <span>{{ item.label }}</span>
            <span v-if="item.label == '超时进行中工单'">{{
              orderCount.timeout_processing_count <= 99 ? orderCount.timeout_processing_count : "0" }}</span>
                <span v-if="item.label == '超时完成工单'">{{
                  orderCount.timeout_completed_count <= 99 ? orderCount.timeout_completed_count : "0" }}</span>
          </li>
        </ul>
      </div>
    </div>
    <div class="orderContent">
      <div class="orderContentLeft content flex flex-col">
        <div style="
            display: flex;
            justify-content: space-between;
            color: #505363;
            font-size: 16px;
            margin-bottom: 10px;
          ">
          <span> {{ currentTitle }} </span> <span>共 {{ total }} 个</span>
        </div>
        <div class="searchStyle">
          <div>
            <el-input v-model="queryParams.roomNumber" placeholder="关键词\房间号" :prefix-icon="Search"
              @keyup.enter="handleQuery" />
          </div>
          <div>
            <el-select v-model="queryParams.slaId" style="width: 100%" placeholder="选择工单类型" @change="handleQuery"
              clearable>
              <el-option v-for="item in slaOptions" :key="item.slaId" :label="item.slaName" :value="item.slaId" />
            </el-select>
          </div>
          <!-- <div>
            <el-select
              v-model="queryParams.responsibleBy"
              style="width: 100%"
              placeholder="责任人"
              @change="handleQuery"
              clearable
            >
              <el-option
                v-for="item in responseOptions"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
          </div> -->
          <div style="flex: 1.5">
            <el-date-picker style="width: 100%" v-model="queryParams.dateTime" type="datetimerange"
              format="YYYY-MM-DD HH:MM" value-format="YYYY-MM-DD HH:MM" range-separator="To" @change="handleQuery"
              start-placeholder="开始时间" end-placeholder="结束时间" />
          </div>
          <div>
            <el-cascader v-model="queryParams.floorList" style="width: 100%" placeholder="选择楼层"
              :props="{ multiple: true }" clearable collapse-tags :show-all-levels="false" :options="floorOptions"
              @change="handleQuery">
            </el-cascader>
          </div>
        </div>
        <div class="orderList flex-1">
          <ul v-infinite-scroll="testLoad">
            <li v-for="(item, index) in orderData" :key="index" @click="listCheck(index, item)"
              :class="currentIndex == index ? 'liStyle grad' : 'liStyle'">
              <div style="width: 150px; text-align: center; margin-right: 10px;margin-top: 20px;">
                <div style="display: flex; justify-content: center; align-items: center">
                  <img :src="item.slaSettingPicUrl"
                    style="width: 40px; height: 40px; border-radius: 50%;margin-bottom: 15px;" />
                </div>
                <div style="font-size: 12px; color: #8a878e">{{ getOrderType(item.slaId) }}</div>
              </div>
              <div class="listDetail">
                <div class="timer_div zc" v-if="item.alarm == 'notEnable'">
                  <span>正常</span>
                </div>
                <div class="timer_div zc" v-else-if="item.alarm =='enable' && item.timeoutFlag == 0">
                  <span>正常</span>
                  <Countdown :time="item.timeOut" @done="handleQuery" />
                </div>
                <div class="timer_div cs" v-else-if="item.alarm =='enable' && item.timeoutFlag == 1">
                  <span>超时</span>
                  <Countdown :time="item.timeOut" mode="timer" />
                </div>
                <div class="textStyle"># {{ item.orderId }}</div>
                <div class="titleStyle" style="font-size: 16px; color: #1d1b20">{{ item.orderTitle }}</div>
                <div class="contentStyle" style="">
                  <div>{{ item.orderDetail }}</div>
                </div>
                <div class="textStyle">创建时间：{{ item.createTime }}</div>
                <div class="textStyle" style="display: flex">
                  <span style="flex: 1"> 创建人：{{ item.createByName }} </span>
                  <span style="flex: 1"> 责任人：{{ item.responsibleByName }} </span>
                </div>
                <div class="textStyle" style="display: flex">
                  <span style="flex: 1"> 房间号：{{ item.roomNumber == 0 ? '' : item.roomNumber }} </span>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <div class="orderContentRight content flex flex-col p-10">
        <div style="border-bottom: 1px solid #cac4d0; padding: 20px 0">
          <el-tag type="primary" v-if="currentTitle == '进行中工单'">{{ "处理中" }}</el-tag>
          <el-tag style="background-color: #f0f9eb; color: #67c23a; border-color: rgb(179, 224.5, 156.5)"
            v-if="currentTitle == '已完成工单'">{{ "已完成" }}</el-tag>
          <el-tag style="background-color: #ecf5ff; color: #409eff; border-color: #409eff"
            v-if="currentTitle == '未处理工单' || currentTitle == '超时进行中工单'">{{ "未处理" }}</el-tag>
          <el-tag style="background-color: #f0f9eb; color: #67c23a; border-color: rgb(179, 224.5, 156.5)"
            v-if="currentTitle == '超时完成工单'">{{ "已完成" }}</el-tag>
          <span class="textStyle" style="margin-left: 10px">工单编号：{{ currentData.orderId }}</span>
        </div>
        <div class="flex-1">
          <div style="font-size: 16px; color: #1d1b20; margin: 20px 0">
            请求内容：{{ currentData.orderTitle }}
          </div>
          <div>
            <el-segmented @change="changeHandle" v-model="currentName" size="large" :options="list" :block="false"
              style="padding: 4px" />
            <div v-if="currentName == '工单详情'" style="font-size: 14px; line-height: 3; padding-top: 20px;width: 100%;">
              <el-row>
                <el-col :span="4">工单类型：</el-col>
                <el-col :span="12">
                  <div style="display: inline-block; vertical-align: middle" v-if="currentData.slaSettingPicUrl">
                    <img :src="currentData.slaSettingPicUrl" style="width: 30px; height: 30px; border-radius: 50%" />
                  </div>
                  {{ getOrderType(currentData.slaId) }}
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="4">房间号：</el-col>
                <el-col :span="12">{{ currentData.roomNumber }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="4">创建时间：</el-col>
                <el-col :span="12">{{ currentData.createTime }}</el-col>
              </el-row>
              <el-row style="width: 100%;">
                <el-col :span="4">描述：</el-col>
                <el-col :span="20">
                  <div class="descStyle">{{ currentData.orderDetail }}</div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="4">创建人：</el-col>
                <el-col :span="12">{{ currentData.createByName }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="4">责任人：</el-col>
                <el-col :span="12">{{ currentData.responsibleByName }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="4">工单处理：</el-col>
                <el-col :span="12" style="display: flex;flex-wrap: wrap;">
                  <el-image v-for="(url, index) in currentData.initUrl" :key="index" :src="url"
                    style="width: 50px;height: 50px;margin-right: 10px;" :preview-src-list="currentData.initUrl"
                    fit="contain">
                    <template #error>
                      <div class="image-error">加载失败</div>
                    </template>
                  </el-image>
                  <!-- <div v-for="(item, index) in currentData.initUrl" :key="index">
                    <img style="width: 50px;height: 50px;margin-right: 10px;" :src="item.url" alt="">
                  </div> -->
                </el-col>
              </el-row>
              <el-row style="margin-top: 10px;">
                <el-col :span="4">工单完成：</el-col>
                <el-col :span="12" style="display: flex;flex-wrap: wrap;">
                  <el-image v-for="(url, index) in currentData.finishUrl" :key="index" :src="url"
                    style="width: 50px;height: 50px;margin-right: 10px;" :preview-src-list="currentData.finishUrl"
                    fit="contain">
                    <template #error>
                      <div class="image-error">加载失败</div>
                    </template>
                  </el-image>
                  <!-- <div v-for="(item, index) in currentData.finishUrl" :key="index">
                    <img style="width: 50px;height: 50px;margin-right: 10px;" :src="item.url" alt="">
                  </div> -->
                </el-col>
              </el-row>
            </div>
            <div v-if="currentName == 'AI对话记录'" class="talkScorll"
              style="font-size: 14px; line-height: 3; padding-top: 20px">
              <AVWaveform v-if="AVWaveformUrl != ''" :src="AVWaveformUrl" :canv-height="0"></AVWaveform>
              <ul>
                <li v-for="(item, index) in aiOptions" :key="index"
                  :class="item.role == 'user' ? 'guestStyle' : 'aiStyle'">
                  <p v-html="item.content"></p>
                </li>
              </ul>
            </div>
            <div v-if="currentName == '流转日志'" style="padding-top: 20px;width: 100%;"  class="logScorll">
              <el-steps style="" direction="vertical" :active="2">
                <ul>
                  <li v-for="(item, index) in orderLogList" :key="index" style="display: flex;line-height: 2;">
                    <div style="flex: 1;justify-items: center;">
                      <img style="width: 25px;height: 25px;border-radius: 50%;line-height: 30px;"
                        src="@/assets/images/start.svg" alt="" v-if="item.status == 0 || item.status == ''">
                      <img style="width: 25px;height: 25px;border-radius: 50%;line-height: 30px;margin-left: -3px;"
                        src="@/assets/images/time.svg" alt="" v-if="item.status == 1">
                      <img style="width: 32px;height: 32px;border-radius: 50%;line-height: 30px;"
                        src="@/assets/images/complete.svg" alt="" v-if="item.status == 2">
                    </div>
                    <div style="flex: 8;margin-left: 15px;" v-if="item.status == 0">
                      <div style="display: flex;justify-content: space-between;align-items: center;">
                        <div>{{ item.content }}</div>
                        <div style="font-size: 12px;color: #8a878e;">{{ item.createTime }}</div>
                      </div>
                      <div
                        :style="index == orderLogList.length - 1 ? 'color:#7a3eeb;font-size:12px;' : 'font-size:12px;'"
                        class="textStyle">发起中</div>
                    </div>
                    <div style="flex: 8;margin-left: 15px;" v-if="item.status == 1">
                      <div style="display: flex;justify-content: space-between;align-items: center;">
                        <div>{{ item.content }}</div>
                        <div style="font-size: 12px;color: #8a878e;">{{ item.createTime }}</div>
                      </div>
                      <div
                        :style="index == orderLogList.length - 1 ? 'color:#7a3eeb;font-size:12px;' : 'font-size:12px;'"
                        class="textStyle">待处理</div>
                    </div>
                    <div style="flex: 8;margin-left: 15px;" v-if="item.status == 2">
                      <div style="display: flex;justify-content: space-between;align-items: center;">
                        <div>{{ item.content }}</div>
                        <div style="font-size: 12px;color: #8a878e;">{{ item.createTime }}</div>
                      </div>
                      <div
                        :style="index == orderLogList.length - 1 ? 'color:#7a3eeb;font-size:12px;' : 'font-size:12px;'"
                        class="textStyle">处理完成</div>
                    </div>
                  </li>
                </ul>
                <!-- <el-step :icon="Clock" />
                <el-step :icon="Picture" /> -->
              </el-steps>
            </div>
          </div>
        </div>
        <div class="text-right border-t p-[10px]">
          <el-button type="primary" @click="handleAction(0)" v-if="currentData.status == '0'">
            开始处理
          </el-button>
          <el-button type="primary" @click="handleAction(2)" v-if="currentData.status == '1'">
            转办
          </el-button>
          <el-button type="primary" @click="handleAction(1)" v-if="currentData.status == '1'">
            处理结束
          </el-button>
        </div>
        <!-- <div class="handleStyle" v-if="currentData.status == '0'">
        </div> -->
        <!-- <div class="handleStyle" v-if="currentData.status == '1'">
          <div>
            <el-button type="primary" @click="handleAction(1)">处理结束</el-button>
          </div>
        </div> -->
      </div>
    </div>

    <el-dialog v-model="dialogVisible" title="新建工单" width="500" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="formRef" label-position="top">
        <el-form-item label="工单标题" prop="orderTitle">
          <el-input :disabled="state.mode === 'end'" v-model="form.orderTitle" style="width: 100%;"
            placeholder="请输入客人请求的内容"></el-input>
        </el-form-item>
        <el-form-item label="工单类型" prop="slaId">
          <el-select :disabled="state.mode === 'end'" v-model="form.slaId" style="width: 100%;" placeholder="请选择工单类型">
            <el-option v-for="item in slaOptions" :key="item.slaId" :label="item.slaName" :value="item.slaId" />
          </el-select>
        </el-form-item>

        <el-form-item label="描述" prop="orderDetail">
          <el-input type="textarea" :disabled="state.mode === 'end'" style="width: 100%;" v-model="form.orderDetail"
            placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="form.roomNumber" :disabled="state.mode === 'end'" placeholder="请输入房间号"
            style="width: 100%;"></el-input>
        </el-form-item>
        <el-form-item label="责任人" prop="responsibleBy">
          <el-tree-select :disabled="state.mode === 'end' || !form.isDepartment" v-model="form.responsibleBy" :data="responseOptions"
            :render-after-expand="false" show-checkbox :props="treeProps" check-strictly check-on-click-node
            node-key='id' filterable style="width: 100%" placeholder="请选择责任人"/>
        </el-form-item>

        <el-form-item label="工单处理" prop="initUrl">
          <el-upload :disabled="state.mode === 'end'" class="upload-demo" :action="uploadUrl"
            :headers="{ Authorization: 'Bearer ' + getToken() }" list-type="picture-card" :on-preview="handlePreview"
            :on-remove="handleRemove" :on-success="handleSuccess" :limit="5" :file-list="form.initUrl"
            :on-exceed="handleExceed" :auto-upload="true" accept="image/*">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <template v-if="state.mode === 'end'">
          <el-form-item label="工单完成" prop="finishUrl">
            <el-upload class="upload-demo" :action="uploadUrl" :headers="{ Authorization: 'Bearer ' + getToken() }"
              list-type="picture-card" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess"
              :limit="5" :file-list="form.finishUrl" :on-exceed="handleExceed" :auto-upload="true" accept="image/*">
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </template>
      </el-form>
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <div class="my-title" v-if="state.mode == 'add'">新建工单</div>
          <div class="my-title" v-else-if="state.mode == 'edit'">指派工单</div>
          <div class="my-title" v-else>结束工单</div>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 图片预览弹窗 -->
    <el-dialog v-model="previewVisible" title="图片预览">
      <img :src="previewImage" style="width: 100%" />
    </el-dialog>
  </div>
</template>
<script setup lang="jsx" name="unprocessedOrder">
import { Calendar, Search, Share } from "@element-plus/icons-vue"
import { Plus } from "@element-plus/icons-vue"
import { Clock, Picture, Upload, VideoPlay } from "@element-plus/icons-vue"
import { reactive, toRaw, ref, onMounted, onBeforeMount, createVNode, computed, nextTick, onActivated } from "vue"
import {
  orderList,
  getSlaList,
  createOrderList,
  getAllocatedList,
  updateOrderList,
  getCount,
  getLogList,
  getAIRecord,
  getAudioFile
} from "@/api/orderCenter"
import { getFloorList } from "@/api/system/setting"
import { deptUserTree } from "@/api/system/role"
import { chatlistAPI, getHistoriesAPI } from "@/api/fastGPT/dataset"
import useUserStore from "@/store/modules/user"
import { shallowRef } from "vue"
import MarkdownIt from "markdown-it"
import Countdown from "@/components/Countdown"
import { AVWaveform } from 'vue-audio-visual'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'

const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/system/order/uploadPicture'


const { proxy } = getCurrentInstance()
const currentIndex = ref()
const currentData = ref({})
const total = ref(0)
const orderData = ref({})
const orderCount = ref({})
const queryParams = ref({
  pageNum: 1,
  pageSize: 4,
  dateTime: undefined,
  responsibleBy: undefined,
  slaId: undefined,
  roomNumber: undefined,
  sort: 1,
  floorList: [],
})

const form = ref({})
const state = reactive({})
const rules = reactive({
  orderTitle: [{ required: true, message: "请输入", trigger: "blur" }],
  slaId: [{ required: true, message: "请输入", trigger: "change" }],
  responsibleBy: [{ required: false, message: "请选择责任人", trigger: "change" }],
})
const slaOptions = ref([])
const aiOptions = ref([])
const responseOptions = ref([])
const currentTitle = ref("未处理工单")
const currentValue = ref(2)
const timeoutFlag = ref()
const currentName = ref("工单详情")
const lists = [
  {
    value: 1,
    label: "我的工单",
  },
  {
    value: 2,
    label: "未处理工单",
  },
  {
    value: 3,
    label: "进行中工单",
  },
  {
    value: 4,
    label: "已完成工单",
  },

]
const problemList = [
  {
    value: 5,
    label: "超时进行中工单",
  },
  {
    value: 6,
    label: "超时完成工单",
  },
]
let statusAndTimoutFlagsObj = {
  1: [
    {
      flag: 0,
      status: 0
    },
    {
      status: 0,
      flag: 1
    },
    {
      flag: 0,
      status: 1
    },
    {
      status: 1,
      flag: 1
    }
  ],
  2: [
    {
      flag: 0,
      status: 0
    },
    {
      status: 0,
      flag: 1
    }
  ],
  3: [
    {
      flag: 0,
      status: 1
    },
    {
      status: 1,
      flag: 1
    }
  ],
  4: [
    {
      flag: 0,
      status: 2
    },
    {
      status: 2,
      flag: 1
    }
  ],
  5: [
    {
      status: 1,
      flag: 1
    }
  ],
  6: [
    {
      status: 2,
      flag: 1
    }
  ]
}
const list = ["工单详情", "AI对话记录", "流转日志"]
const dialogVisible = ref(false)
const visible = ref(false)
const treeProps = {
  value: 'id',
  label: 'label',
  children: 'children',
  // 可选：禁用用户节点选择
  disabled: (data) => !data.isUser
};

const AVWaveformUrl = ref('')

const floorOptions = ref([])
const getFloorListFn = () => {
  getFloorList().then((response) => {
    floorOptions.value = traverseTree([response.data])
  })
}
getFloorListFn()

/** 获取工单列表 */
function getOrderList() {
  queryParams.value.pageNum = 1
  let floorList = queryParams.value.floorList.map((item) => {
    return item[2]
  })

  orderList({
    ...queryParams.value,
    createTime: queryParams.value.dateTime && queryParams.value.dateTime[0],
    doneTime: queryParams.value.dateTime && queryParams.value.dateTime[1],
    statusAndTimoutFlags:statusAndTimoutFlagsObj[currentValue.value === 0 ? timeoutFlag.value : currentValue.value],
    floorList: floorList
  }).then(async (response) => {
    orderData.value = response.rows
    total.value = response.total
  })
  getCountData()
}
// 获取工单类型
getSlaList().then((response) => {
  slaOptions.value = response.rows
})
// 获取工单数量
function getCountData() {
  let floorList = queryParams.value.floorList.map((item) => {
    return item[2]
  })
  getCount({...queryParams.value,floorList:floorList}).then((response) => {
    orderCount.value = response
  })
}
function transformDeptTree(deptNode, isRoot = false) {
  // 1. 处理当前部门节点
  const transformedNode = {
    id: deptNode.deptId,
    label: deptNode.deptName,
    children: []
  };

  // 2. 合并用户到同层级children（优先处理用户）
  if (deptNode.userList?.length > 0) {
    transformedNode.children.push(
      ...deptNode.userList.map(user => ({
        id: user.userId,
        label: `${user.nickName} (${user.userName})`,
        isUser: true
      }))
    );
  }

  // 3. 递归处理子部门
  if (deptNode.children?.length > 0) {
    transformedNode.children.push(
      ...deptNode.children.map(child => transformDeptTree(child))
    );
  }

  // 4. 根节点特殊处理：将第一个子元素移到最前
  if (isRoot && transformedNode.children.length > 0) {
    const firstChild = transformedNode.children.shift();
    transformedNode.children.unshift(firstChild); // 显式确保顺序
  }

  // 5. 处理空children
  if (transformedNode.children.length === 0) {
    delete transformedNode.children;
  }

  return transformedNode;
}
const userDeptInfo = ref()
const userInfo = ref()
onMounted(() => {
  useUserStore().getInfo().then((res) => {
    userDeptInfo.value = res.user.dept.deptId
    userInfo.value = res.user
    // 获取责任人
    deptUserTree({ deptId: userDeptInfo.value }).then((response) => {
      responseOptions.value = [transformDeptTree(response.data, true)];
    })
  })

})
// 相当于 created 阶段
onBeforeMount(() => {
  // getCountData()
  getOrderList()
});

function listClick(label, value, flag) {
  queryParams.value.pageNum = 1
  currentIndex.value = null
  currentData.value = {}
  currentTitle.value = label
  aiOptions.value = []
  let floorList = queryParams.value.floorList.map((item) => {
    return item[2]
  })
  if (flag) {
    timeoutFlag.value = value
    currentValue.value = 0
    orderList({ ...queryParams.value, floorList, statusAndTimoutFlags:statusAndTimoutFlagsObj[currentValue.value === 0 ? timeoutFlag.value : currentValue.value],
 }).then((response) => {
      orderData.value = response.rows
      total.value = response.total
    })
  } else {
    currentValue.value = value
    timeoutFlag.value = 0
    let roleId = null
    if(label == '我的工单'){
      roleId = userInfo.value.roles[0].roleId
    }
    orderList({ ...queryParams.value,  floorList, statusAndTimoutFlags:statusAndTimoutFlagsObj[currentValue.value === 0 ? timeoutFlag.value : currentValue.value], responsibleBy:roleId
 }).then((response) => {
      orderData.value = response.rows
      total.value = response.total
    })
  }
}

// 流转日志数据list
const orderLogList = ref()
const listCheck = (index, item) => {
  currentIndex.value = index
  currentData.value = JSON.parse(JSON.stringify(item))
  if (currentData.value.initUrl) {
    if (!Array.isArray(currentData.value.initUrl)) {
      currentData.value.initUrl = currentData.value.initUrl.split(";").filter(item => item !== "");
      // currentData.value.initUrl = initUrl.map((item) => {
      //   // import.meta.env.VITE_APP_BASE_API + 
      //   return {
      //     name: item,
      //     url: item,
      //   }
      // })
    }
  } else {
    currentData.value.initUrl = []
  }

  if (currentData.value.finishUrl) {
    if (!Array.isArray(currentData.value.finishUrl)) {
      currentData.value.finishUrl = currentData.value.finishUrl.split(";").filter(item => item !== "");
      // currentData.value.finishUrl = finishUrl.map((item) => {
      //   return {
      //     name: item,
      //     url: item,
      //   }
      // })
    }
  } else {
    currentData.value.finishUrl = []
  }
  getLogList(item.orderId).then((response) => {
    // getLogList(33).then((response) => {
    orderLogList.value = response.data
  })
  getAIRecord({
    orderId: item.orderId
  }).then((res) => {
    if (currentName.value === 'AI对话记录' && currentData.value.orderId) {
      getAudioFileMp3()
    }
    const md = new MarkdownIt()
    aiOptions.value =  res.data ? res.data.map((obj) => {
      return { content: md.render(obj.content), role: obj.role }
    }) : []

  })
}

const previewImage = ref('')
const previewVisible = ref(false)

function handlePreview(file) {
  previewImage.value = file.url || file.response?.url
  previewVisible.value = true
}

function handleRemove(file, fileList) {
  if (state.mode === 'end') {
    form.value.finishUrl = fileList
  } else {
    form.value.initUrl = fileList
  }
}

function handleSuccess(response, file, fileList) {
  // 上传成功后的文件列表
  if (state.mode === 'end') {
    form.value.finishUrl = fileList
  } else {
    form.value.initUrl = fileList
  }
}

function handleExceed(files, fileList) {
  ElMessage.warning('最多上传 5 张图片')
}
// 新建工单提交
const submitHandle = () => {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (state.mode == "add") {
        let params = JSON.parse(JSON.stringify(form.value))
        if (form.value.initUrl) {
          let initUrl = form.value.initUrl.map((item) => {
            return item.response.imgUrl
          })
          params.initUrl = initUrl.join(";")
        } else {
          params.initUrl = ""
        }

        if (Array.isArray(params.finishUrl)) {
          params.finishUrl = params.finishUrl.join(";")
        }
        createOrderList(params)
          .then((response) => {
            if (response.code == 200) {
              dialogVisible.value = false
              proxy.$modal.msgSuccess("新增成功")
              getOrderList()
            }
          })
          .catch(() => { })
      } else {
        let params = JSON.parse(JSON.stringify(form.value))
        let initUrl = form.value.initUrl.map((item) => {
          if (item.response) {
            return item.response.imgUrl
          } else {
            return item.url.replace(import.meta.env.VITE_APP_BASE_API, "")
          }
        })
        params.initUrl = initUrl.join(";")
        if (Array.isArray(params.finishUrl)) {
          params.finishUrl = params.finishUrl.join(";")
        }
        if (state.mode == "edit") {
          params.status = 1
          updateOrderList(params)
            .then((response) => {
              if (response.code == 200) {
                dialogVisible.value = false
                proxy.$modal.msgSuccess("操作成功")
                getOrderList()
              }
            })
            .catch(() => { })
        } else {
          params.orderId = currentData.value.orderId
          params.mark = currentData.value.mark
          params.responsibleBy = currentData.value.responsibleBy
          params.timeoutFlag = currentData.value.timeoutFlag
          params.status = 2
          let finishUrl = form.value.finishUrl.map((item) => {
            if (item.response) {
              return item.response.imgUrl
            } else {
              return item.url.replace(import.meta.env.VITE_APP_BASE_API, "")
            }
          })
          params.finishUrl = finishUrl.join(";")
          console.log(params, 'params');

          proxy.$modal
            .confirm("确认当前工单处理结束？")
            .then(() => {
              updateOrderList(params)
                .then((response) => {
                  if (response.code == 200) {
                    dialogVisible.value = false
                    proxy.$modal.msgSuccess("处理成功")
                    getOrderList()
                  }
                })
                .catch(() => { })
            })
            .catch(() => { })
        }
      }
    }
  })
}
// 开始处理
const handleAction = (type) => {
  if (type == 0) {
    dialogVisible.value = true
    state.mode = "edit"
    form.value = JSON.parse(JSON.stringify(currentData.value))
    form.value.responsibleBy =
      currentData.value.responsibleBy !== '未指定负责人' ? Number(currentData.value.responsibleBy) : userInfo.value.userId
    form.value.isDepartment = userInfo.value.roles[0].roleKey == "department"
    rules.responsibleBy[0].required = true
    if (!Array.isArray(currentData.value.initUrl)) {
      if (currentData.value.initUrl) {
        let initUrl = currentData.value.initUrl.split(";")
        form.value.initUrl = initUrl.map((item) => {
          return {
            name: item,
            url: item,
          }
        })
      } else {
        form.value.initUrl = []
      }
    }else{
      if (currentData.value.initUrl) {
        form.value.initUrl = currentData.value.initUrl.map((item) => {
          return {
            name: item,
            url: item,
          }
        })
      } else {
        form.value.initUrl = []
      }
    }
  } else if (type == 1) {
    dialogVisible.value = true
    state.mode = "end"
    form.value = JSON.parse(JSON.stringify(currentData.value))
    form.value.responsibleBy = currentData.value.responsibleBy && Number(currentData.value.responsibleBy)
    rules.responsibleBy[0].required = true
    if (currentData.value.initUrl) {
      if (Array.isArray(currentData.value.initUrl)) {
        form.value.initUrl = currentData.value.initUrl.map((item) => {
          return {
            name: item,
            url: item,
          }
        })
      } else {
        let initUrl = currentData.value.initUrl.split(";")
        form.value.initUrl = initUrl.map((item) => {
          return {
            name: item,
            url: item,
          }
        })
      }
    } else {
      form.value.initUrl = []
    }

    form.value.finishUrl = []

  } else {
    dialogVisible.value = true
    state.mode = "edit"
    form.value = JSON.parse(JSON.stringify(currentData.value))
    form.value.responsibleBy =
      currentData.value.responsibleBy && Number(currentData.value.responsibleBy)
    rules.responsibleBy[0].required = true
    form.value.isDepartment = true
    if (currentData.value.initUrl) {
      if (Array.isArray(currentData.value.initUrl)) {
        form.value.initUrl = currentData.value.initUrl.map((item) => {
          return {
            name: item,
            url: item,
          }
        })
      } else {
        let initUrl = currentData.value.initUrl.split(";")
        form.value.initUrl = initUrl.map((item) => {
          return {
            name: item,
            url: item,
          }
        })
      }
    } else {
      form.value.initUrl = []
    }

  }
}

const changeHandle = (val) => {
  currentName.value = val
  if (currentName.value === 'AI对话记录' && currentData.value.orderId) {
    getAudioFileMp3()
  }
}

const getAudioFileMp3 = () => {
  getAudioFile(currentData.value.orderId).then((res) => {
    if (res.size > 0) {
      const blob = new Blob([res], { type: 'audio/mp3' }) // 或其他类型，如 audio/wav
      AVWaveformUrl.value = URL.createObjectURL(blob)
    } else {
      AVWaveformUrl.value = ''
    }
  })
}

const addAction = () => {
  proxy.resetForm("formRef")
  form.value = {}
  form.value.isDepartment = true
  dialogVisible.value = true
  state.mode = "add"
}
const getResponseName = (value) => {
  return (
    responseOptions.value.filter((obj) => obj.userId == value)[0] &&
    responseOptions.value.filter((obj) => obj.userId == value)[0].nickName
  )
}
const getOrderType = (value) => {
  return (
    slaOptions.value.filter((obj) => obj.slaId == value)[0] &&
    slaOptions.value.filter((obj) => obj.slaId == value)[0].slaName
  )
}
/** 搜索按钮操作 */
function handleQuery() {
  getOrderList()
}

const testLoad = () => {
  if (total.value) {
    if (total.value > orderData.value.length) {
      queryParams.value.pageNum = queryParams.value.pageNum + 1
      let floorList = queryParams.value.floorList.map((item) => {
        return item[2]
      })
      orderList({
        ...queryParams.value,
        createTime: queryParams.value.dateTime && queryParams.value.dateTime[0],
        doneTime: queryParams.value.dateTime && queryParams.value.dateTime[1],
        floorList,
        statusAndTimoutFlags:statusAndTimoutFlagsObj[currentValue.value === 0 ? timeoutFlag.value : currentValue.value]
      }).then(async (response) => {
        orderData.value = orderData.value.concat(response.rows)
        total.value = response.total
      })
    } else {
      // this.$message({
      //   showClose: false,
      //   // message: "已经到底了",
      //   type: "warning",
      //   duration: 1500
      // });
    }
  } else {
    // console.log("123456");
  }
}

function traverseTree(tree) {
  // 遍历树的每个节点
  tree.forEach(node => {
    if (node.deptId && node.deptName) {
      node.value = node.deptId
      node.label = node.deptName
    }
    if (node.buildingId && node.buildingName) {
      node.value = node.buildingId
      node.label = node.buildingName
    }
    if (node.floorId && node.floorName) {
      node.value = node.floorId
      node.label = node.floorName
    }
    // 如果当前节点有子节点，递归调用
    node.children = node.buildingList || node.floorList // 确保children存在
    if (node.children && node.children.length > 0) {
      traverseTree(node.children);
    }
  });

  return tree
}

</script>
<style scoped lang="scss">
.app-container {
  // height: 100%;
  height: calc(100vh - 85px);
  // width: 100%;
  background-color: #f7f2fa;
  display: flex;

  .orderCenterList {
    width: 200px;
    // height: calc(100% + 45px);
    // text-align: center;
    background-color: #fff;
    padding: 0 6px 0 10px;
    box-sizing: border-box;
    margin-right: 20px;
    margin-top: -25px;
    margin-left: -25px;
    font-size: 14px;

    ul {
      margin: 0;
      padding: 0 0 10px 0;

      li {
        display: flex;
        justify-content: space-between;
        line-height: 3;
        padding: 0 8px 0 15px;
        border-radius: 4px;
        cursor: pointer;
      }

      .bgColor {
        background-color: #e8def8;
      }
    }
  }

  .orderContent {
    // height: calc(100% + 10px);
    flex: 7;
    display: flex;

    .content {
      flex: 1;
    }

    .orderContentLeft {
      // max-height: 100%;
      flex: 1;
      margin-right: 10px;

      .searchStyle {
        display: flex;

        div {
          flex: 1;
        }

        div:nth-child(1) {
          flex: 1.2;
          margin-right: 10px;

          .el-select__wrapper {
            width: 100%;
          }
        }

        div:nth-child(2) {
          flex: 1;
          margin-right: 10px;
        }

        div:nth-child(3) {
          flex: 1;
          margin-right: 10px;
        }

        ::v-deep .el-cascader .el-input {
          height: 32px;
        }
      }

      .orderList {
        height: calc(100% - 320px);
        overflow: scroll;
        user-select: none;
        margin-top: 10px;

        &::-webkit-scrollbar {
          width: 4px;
          height: 0px;
          margin-top: 5px;
          background: #f7f7f9;
        }

        &::-webkit-scrollbar-track-piece {
          /*滚动条背景颜色*/
          background: #f7f7f9;
        }

        &::-webkit-scrollbar-thumb {
          /* 滑块 */
          border-radius: 5px;
          height: 50px;
          width: 20px;
          // box-shadow: inset 0 0 0px #606987;
          background: #d4d9e2;
        }

        ul {
          width: 100%;
          padding: 0;
          margin-top: 0px;

          .grad {
            background-image: linear-gradient(to right, #e9dff8, #fffeff);
          }

          .liStyle {
            width: 100%;
            height: 190px;
            margin-bottom: 10px;
            padding: 20px 20px 20px 0;
            background-color: #ffffff;
            display: flex;
            border-radius: 8px;

            // div {
            //   flex: 1;
            //   margin-bottom: 10px;
            // }
            .listDetail {
              flex: 1;
              position: relative;

              .titleStyle {
                word-break: break-all;
                display: -webkit-box;
                /* 设置为WebKit内核的弹性盒子模型 */
                -webkit-box-orient: vertical;
                /* 垂直排列 */
                -webkit-line-clamp: 1;
                /* 限制显示两行 */
                overflow: hidden;
                /* 隐藏超出范围的内容 */
                text-overflow: ellipsis;
                /* 使用省略号 */
              }

              .contentStyle {
                font-size: 14px;
                color: #1d1b20;
                word-break: break-all;
                display: -webkit-box;
                /* 设置为WebKit内核的弹性盒子模型 */
                -webkit-box-orient: vertical;
                /* 垂直排列 */
                -webkit-line-clamp: 2;
                /* 限制显示两行 */
                overflow: hidden;
                /* 隐藏超出范围的内容 */
                text-overflow: ellipsis;
                /* 使用省略号 */
              }

              .timer_div {
                position: absolute;
                right: 0;
                top: 0;
                padding: 5px 20px;
                display: flex;
                font-size: 14px;
              }

              .zc {
                color: #52b58b;
                border: 1px solid #52b58b;
                background-color: #e3f9e9;
              }

              .gj {
                color: #e88c42;
                border: 1px solid #e88c42;
                background-color: #fff1e9;
              }

              .cs {
                color: #da5d56;
                border: 1px solid #da5d56;
                background-color: #fff0ed;
              }
            }
          }
        }
      }
    }

    .image-error {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      background-color: #f5f5f5;
      color: #999;
    }

    .descStyle {
      word-break: break-all;
      line-height: 1.5;
      display: -webkit-box;
      /* 设置为WebKit内核的弹性盒子模型 */
      -webkit-box-orient: vertical;
      /* 垂直排列 */
      // -webkit-line-clamp: 3; /* 限制显示两行 */
      overflow: hidden;
      /* 隐藏超出范围的内容 */
      text-overflow: ellipsis;
      /* 使用省略号 */
    }

    .orderContentRight {
      // height: 100%;
      flex: 1;
      width: 100%;
      padding: 0 20px;
      border-radius: 8px;
      background-color: #ffffff;

      .demo-tabs {
        .el-tabs__nav-wrap {
          .el-tabs__nav-scroll {
            background-color: #fff5de;
            border-radius: 6px;
            padding: 10px;

            .el-tabs__item .is-active {
              background-color: #fff5de;
            }
          }
        }
      }

      .handleStyle {
        width: 41%;
        padding: 20px 0;
        position: fixed;
        bottom: 20px;
        border-top: 1px solid #ccc;
        text-align: right;

        div {
          position: fixed;
          bottom: 15px;
          right: 30px;
        }
      }

      .talkScorll {
        .audio {
          width: 50%;
        }

        ul {
          padding: 0 20px;
          margin-top: 0px;
          height: calc(100vh - 400px) !important;
          overflow: scroll;
          user-select: none;
          margin-top: 10px;

          &::-webkit-scrollbar {
            width: 4px;
            height: 0px;
            margin-top: 5px;
            background: #f7f7f9;
          }

          &::-webkit-scrollbar-track-piece {
            /*滚动条背景颜色*/
            background: #f7f7f9;
          }

          &::-webkit-scrollbar-thumb {
            /* 滑块 */
            border-radius: 5px;
            height: 50px;
            width: 20px;
            // box-shadow: inset 0 0 0px #606987;
            background: #d4d9e2;
          }

          .aiStyle {
            p {
              display: inline-block;
              padding: 3px 20px;
              border: 1px solid #cac4d0;
              background-color: #e8def8;
              border-radius: 20px;
              margin: 5px 0;
              line-height: 30px;
            }
          }

          .guestStyle {
            text-align: right;

            p {
              display: inline-block;
              padding: 3px 20px;
              border: 1px solid #cac4d0;
              background-color: #fff;
              border-radius: 20px;
              line-height: 30px;
            }
          }
        }
      }
      .logScorll {
        .audio {
          width: 50%;
        }

        ul {
          padding: 0 20px;
          margin-top: 0px;
          height: calc(100vh - 350px) !important;
          overflow: scroll;
          user-select: none;
          margin-top: 10px;

          &::-webkit-scrollbar {
            width: 4px;
            height: 0px;
            margin-top: 5px;
            background: #f7f7f9;
          }

          &::-webkit-scrollbar-track-piece {
            /*滚动条背景颜色*/
            background: #f7f7f9;
          }

          &::-webkit-scrollbar-thumb {
            /* 滑块 */
            border-radius: 5px;
            height: 50px;
            width: 20px;
            // box-shadow: inset 0 0 0px #606987;
            background: #d4d9e2;
          }

          // .aiStyle {
          //   p {
          //     display: inline-block;
          //     padding: 3px 20px;
          //     border: 1px solid #cac4d0;
          //     background-color: #e8def8;
          //     border-radius: 20px;
          //     margin: 5px 0;
          //     line-height: 30px;
          //   }
          // }

          // .guestStyle {
          //   text-align: right;

          //   p {
          //     display: inline-block;
          //     padding: 3px 20px;
          //     border: 1px solid #cac4d0;
          //     background-color: #fff;
          //     border-radius: 20px;
          //     line-height: 30px;
          //   }
          // }
        }
      }
    }
  }
}

.upload-demo {
  width: 100%;

  :deep(.el-upload-list) {
    .el-upload-list__item {
      width: 80px;
      height: 80px;
    }

    .el-upload {
      width: 80px !important;
      height: 80px !important;
    }
  }
}

.my-header {
  height: 50px;
  display: flex;
  flex-direction: row;

  justify-content: space-between;
  gap: 16px;

  .my-title {
    font-size: 18px;
    font-weight: 600;
  }
}

.el-form-item {
  :deep(.el-form-item__error) {
    top: 10;
  }
}

.textStyle {
  font-size: 14px;
  color: #8a878e;
}

.el-segmented {
  width: 100%;
  background-color: #fff5de;
  --el-border-radius-base: 8px;
  --el-segmented-item-selected-bg-color: #fff;
  --el-segmented-item-selected-color: #0f172a;

  &:deep() {
    .el-segmented__group {
      width: auto;

      .el-segmented__item {
        font-size: 14px;
      }
    }
  }
}

.el-steps {
  &:deep() {
    .is-finish {
      border-color: #cad2e0;
    }
  }
}
</style>
